#include "CBL_Profile.h"
#include <stdio.h>

CB_SUBNAMESPACE_START(Debug)

void CProfileManager::AddMeasurement(const char* _Key, double _TimeMs)
{
	CB_CRITICAL_SECTION_GUARD(m_AddMutex);
	
	IdType Id = m_Keys.RegisterId(_Key);
	
	if ((IdType)m_Items.Size() == Id)
	{
		SProfileItem Item = { _TimeMs, 1, _Key };
		m_Items.PushBack(Item);
	}
	else 
	{
		SProfileItem& rItem = m_Items[Id];
		rItem.m_TimeUsed += _TimeMs;
		++rItem.m_Calls;
	}
}

// ----------------------------------------------------------------------------------------------

void CProfileManager::PrintReport()
{
	printf("- Profiling report ------------------------------------------------------------\n");
	printf("  ID Name                                     Calls      Total(ms)  Average(ms)\n");
	printf("-------------------------------------------------------------------------------\n");
	
	uint32 NumItems = m_Items.Size();
	for (uint32 ItemIdx=0; ItemIdx<NumItems; ++ItemIdx)
	{
		SProfileItem& rItem = m_Items[ItemIdx];
		
		double Average = rItem.m_TimeUsed / rItem.m_Calls;
		
		printf("%4d %-40s %-7d %12.2f %12.2f\n", ItemIdx, rItem.m_Name, rItem.m_Calls, rItem.m_TimeUsed, Average);
	}
}

// ----------------------------------------------------------------------------------------------

CProfileManager::CProfileManager()
{
}

// ----------------------------------------------------------------------------------------------

CProfileManager::~CProfileManager()
{
}

CB_SUBNAMESPACE_END